package com.homestay.controller;

import com.google.gson.Gson;
import com.homestay.beans.Books;
import com.homestay.beans.Home;
import com.homestay.beans.Order;
import com.homestay.beans.Vip;
import com.homestay.exception.UserException;
import com.homestay.service.BooksService;
import com.homestay.service.HomeService;
import com.homestay.service.VipService;
import com.homestay.service.impl.BooksServiceImpl;
import com.homestay.service.impl.HomeServiceImpl;
import com.homestay.service.impl.VipServiceImpl;
import com.homestay.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/book")
public class BooksServlet extends HttpServlet {

    BooksService booksService = new BooksServiceImpl();

    VipService vipService = new VipServiceImpl();
    HomeService homeService = new HomeServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String action = req.getParameter("action");
        switch (action) {
            case "loadData":
                booksLoadData(req, resp);
                break;
            case "add":
                booksAdd(req, resp);
                break;
            case "query":
                booksQuery(req, resp);
                break;
            case "delete":
                booksDelete(req, resp);
                break;
            case "goUpdate":
                goUpdate(req, resp);
                break;
            case "update":
                bookUpdate(req, resp);
                break;
            case "exitHome":
                exitHome(req, resp);
                break;
            default:
                break;
        }
    }

    private void exitHome(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String home_id = req.getParameter("home_id");
        // 更新退房时间为当前时间,同时更新房间状态为未打扫
        try {
            JdbcUtils.startTransaction();
            JdbcUtils.executeUpdate("update tb_books set exitTime = now() where id = ?", id);
            JdbcUtils.executeUpdate("update tb_home set state = '未打扫' where id = ?", home_id);
            JdbcUtils.commitTransaction();
            JdbcUtils.close();
        } catch (Exception e) {
            JdbcUtils.rollbackTransaction();
            resp.getWriter().write("false");
            throw new RuntimeException(e);
        }
        Books books = booksService.queryBookById(id);
        resp.getWriter().write(new Gson().toJson(books));
    }

    private void bookUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String vip_id = req.getParameter("vip_id");
        String home_id = req.getParameter("home_id");
        String enterTime = req.getParameter("enterTime");
        String exitTime = req.getParameter("exitTime");
        Books books;
        if("".equals(exitTime)){
            books = new Books(Integer.parseInt(id),Integer.parseInt(vip_id), Integer.parseInt(home_id), LocalDateTime.parse(enterTime));
        } else{
            books = new Books(Integer.parseInt(id),Integer.parseInt(vip_id), Integer.parseInt(home_id), LocalDateTime.parse(enterTime), LocalDateTime.parse(exitTime));
        }
        int count = booksService.update(books);
        if(count > 0){
            resp.getWriter().write("true");
        } else {
            resp.getWriter().write("false");
        }
    }

    private void goUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Order order = booksService.queryById(id);
        List<Vip> vips = vipService.query("", "", "");
        List<Home> homeList = homeService.query("", "空房", "");
        req.setAttribute("order", order);
        req.setAttribute("vips", vips);
        req.setAttribute("homeList", homeList);
        req.getRequestDispatcher("/views/guests_update.jsp").forward(req, resp);
    }

    private void booksDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        try {
            int count = booksService.delete(id);
            if(count > 0){
                resp.getWriter().write("true");
            }else{
                resp.getWriter().write("false");
            }
        } catch (UserException e) {
            resp.getWriter().write(e.getMessage());
        }
    }

    private void booksQuery(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String card = req.getParameter("card");
        String phone = req.getParameter("phone");
        if(name == null || name.isEmpty()){
            name = "";
        }
        if(card == null || card.isEmpty()){
            card = "";
        }
        if(phone == null || phone.isEmpty()){
            phone = "";
        }
        List<Order> booksList = booksService.query(name, card, phone);
        //System.out.println(booksList.toString());
        //将数据转换为json格式返回给客户端
        resp.getWriter().write(new Gson().toJson(booksList));
    }

    private void booksAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String vip_id = req.getParameter("vip_id");
        String home_id = req.getParameter("home_id");
        String enterTime = req.getParameter("enterTime");
        //String exitTime = req.getParameter("exitTime");
        //System.out.println("vip_id:" + vip_id + " ,home_id:" + home_id + " ,enterTime:" + enterTime);

        Books books = new Books(Integer.parseInt(vip_id), Integer.parseInt(home_id), LocalDateTime.parse(enterTime));
        int count = booksService.add(books);
        if (count > 0) {
            resp.getWriter().write("true");
        } else {
            resp.getWriter().write("false");
        }
    }

    private void booksLoadData(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        List<Vip> vips = vipService.query("", "", "");
        List<Home> homeList = homeService.query("", "空房", "");
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("vips", vips);
        data.put("homeList", homeList);
        // 把数据转换成json，发送给客户端
        resp.getWriter().write(new Gson().toJson(data));

    }
}
